<template>
  <div v-if="checkoutDtoInfo" class="approval-page">
    <!-- 左侧信息列 -->
    <div class="left-column">
      <!-- 基本信息卡片 -->
      <div>
        <!-- 基本信息 -->
        <div class="info-card">
          <h3 class="card-title">基本信息</h3>
          <ul class="info-list">
            <li>
              <span class="label">单据编号</span>
              <span class="value">{{ checkoutDtoInfo.checkoutNo }}</span>
            </li>
            <li>
              <span class="label">老人姓名</span>
              <span class="value">{{ checkoutDtoInfo.name }}</span>
            </li>
            <li>
              <span class="label">老人身份证号</span>
              <span class="value">{{ checkoutDtoInfo.idCardNo }}</span>
            </li>
            <li>
              <span class="label">联系方式</span>
              <span class="value">{{ checkoutDtoInfo.contact }}</span>
            </li>
            <li>
              <span class="label">费用期限</span>
              <span class="value">
            {{ formatDate(checkoutDtoInfo.stayStart) }} ——— {{ formatDate(checkoutDtoInfo.stayEnd) }}
          </span>
            </li>
            <li>
              <span class="label">护理等级</span>
              <span class="value">{{ checkoutDtoInfo.careLevel }}</span>
            </li>
            <li>
              <span class="label">入住床位</span>
              <span class="value">{{ checkoutDtoInfo.bedNo }}床位</span>
            </li>
            <li>
              <span class="label">签约合同</span>
              <span class="value">
            {{ checkoutDtoInfo.name ? checkoutDtoInfo.name + "的入住合同" : '暂无合同' }}
            <a v-if="checkoutDtoInfo.contract?.agreementUrl" :href="checkoutDtoInfo.contract.agreementUrl" target="_blank" class="view-link">查看</a>
          </span>
            </li>
            <li>
              <span class="label">养老顾问</span>
              <span class="value">{{ checkoutDtoInfo.consultant || '——' }}</span>
            </li>
            <li>
              <span class="label">护理员</span>
              <span class="value">{{ checkoutDtoInfo.caregiverName }}</span>
            </li>
          </ul>
        </div>

        <!-- 申请信息 -->
        <div class="info-card" style="margin-top: 20px;">
          <h3 class="card-title">申请信息</h3>
          <ul class="info-list">
            <li>
              <span class="label">退住日期</span>
              <span class="value">{{ checkoutDtoInfo.checkoutTime }}</span>
            </li>
            <li>
              <span class="label">退住原因</span>
              <span class="value">{{ checkoutDtoInfo.checkoutReason }}</span>
            </li>
            <li>
              <span class="label">备注</span>
              <span class="value">{{ checkoutDtoInfo.remark || '无' }}</span>
            </li>
            <li>
              <span class="label">申请人</span>
              <span class="value">{{ checkoutDtoInfo.applicant }}</span>
            </li>
            <li>
              <span class="label">申请时间</span>
              <span class="value">{{ formatDateTime(checkoutDtoInfo.applyTime) }}</span>
            </li>
          </ul>
        </div>

        <!-- 解除记录 -->
        <div class="info-card" style="margin-top: 20px;">
          <h3 class="card-title">解除记录</h3>
          <ul class="info-list">
            <li>
              <span class="label">提交人</span>
              <span class="value">{{ checkoutDtoInfo.contract?.terminateBy || '——' }}</span>
            </li>
            <li>
              <span class="label">解除日期</span>
              <span class="value">{{ formatDate(checkoutDtoInfo.contract?.terminateDate) }}</span>
            </li>
            <li>
              <span class="label">解除协议</span>
              <span class="value">
            {{ checkoutDtoInfo.name ? checkoutDtoInfo.name +"的退住协议" : '暂无协议' }}
            <a v-if="checkoutDtoInfo.contract?.terminateAgreementUrl" :href="checkoutDtoInfo.contract.terminateAgreementUrl" target="_blank" class="view-link">查看</a>
          </span>
            </li>
          </ul>
        </div>
      </div>

      <!-- 账单明细卡片 -->
      <div  class="info-card" style="margin-top: 20px;">
        <h3 class="card-title">账单明细</h3>
        <!-- 应退分组 -->
        <div v-if=" refundBill.good && refundBill.good.length>0" class="bill-section">
          <div class="section-header">
            应退
            <span class="todo-count">待办：{{ refundBill.good.length+1 }}</span>
            <span class="total-amount">小计：{{(billJson.monthBill.payableActual || 0) +
            (billJson.refundBill.good.reduce((sum, item) => sum + (item.payableAmount || 0), 0)) }}元</span>
          </div>
          <div class="bill-item">
            <p>账单编号：{{ billJson.monthBill.tradeOrderNo || billJson.monthBill.billNo }}
              <span class="bill-type">月度账单</span>
            </p>
            <p>账单月份：{{ billJson.monthBill.billMonth }}</p>
            <p>可退金额：{{ billJson.monthBill.payableActual }}元</p>
            <p>实际天数：{{ billJson.monthBill.actualDays || 0 }}天</p>
            <p>退款天数：{{ billJson.monthBill.unStayDays || 0 }}天</p>
            <p>实退金额：{{ billJson.refundAmount1 }} 元</p>
            <p>调整备注：{{ billJson.adjustRemark1 || '无' }}</p>
          </div>

          <!-- 费用账单（循环渲染 billJson.refundBill.good 列表） -->
          <div class="bill-item" v-for="(item, index) in billJson.refundBill.good" :key="index">
            <p>账单编号：{{ item.tradeOrderNo || item.billNo }}
              <el-button type="text" size="mini">费用账单</el-button>
            </p>
            <p>护理项目名称：{{ item.extend1 || '无' }}</p>
            <p>可退金额：{{ item.payableAmount }}元</p>
          </div>
        </div>

        <!-- 欠费分组 -->
        <div v-if="billJson.unPayBill" class="bill-section" style="margin-top: 15px;">
          <div class="section-header">
            欠费
            <!-- 待办数量：欠费月度账单列表长度 -->
            <span class="todo-count">待办：{{ billJson.unPayBill.month.length }}</span>
            <!-- 欠费小计：所有欠费账单应付金额总和 -->
            <span class="total-amount">小计：{{
                billJson.unPayBill.month.reduce((sum, item) => sum + (item.payableAmount || 0), 0)
              }}元</span>
          </div>
          <div class="bill-item" v-for="(item, index) in billJson.unPayBill.month" :key="index">
            <p>账单编号：{{ item.tradeOrderNo || item.billNo }}
              <el-button type="text" size="mini">月度账单</el-button>
            </p>
            <p>账单月份：{{ item.billMonth }}</p>
            <p>应付金额：{{ item.payableAmount }}元</p>
          </div>
        </div>
        <!--        <p>可退押金：{{ billJson.balance.arrearsAmount }}元</p>-->
        <!--        <p>预缴费：{{ billJson.balance.prepaidBalance }}元</p>-->
        <!--        <p>调整备注：{{ billJson.adjustRemark2 || '无' }}</p>-->
        <!--        <p>实退金额：{{ billJson.refundAmount2 }}元</p>-->
        <!-- 余额分组 -->
        <div v-if="billJson.balance" class="bill-section" style="margin-top: 15px;">
          <div class="section-header">
            余额
            <span class="total-amount">小计：{{billJson.balance.prepaidBalance+billJson.refundAmount2}}元</span>
          </div>
          <div class="bill-item">
            <p>可退押金：{{ billJson.balance.arrearsAmount }}元</p>
            <p>调整备注：{{ billJson.adjustRemark2 || '无' }}</p>
            <p>实退金额：{{ billJson.refundAmount2 }}元</p>
          </div>
          <div class="bill-item">
            <p>预缴费：{{ billJson.balance.prepaidBalance }}元</p>
          </div>
        </div>

        <!-- 最终金额提示 -->
        <div class="final-amount">
          最终退款金额 = 应退 - 欠费 + 余额 = {{total}}元
        </div>
      </div>
    </div>

    <!-- 右侧审批列 -->
    <div  class="right-column">
      <!-- 审批结果卡片 -->
      <div v-if="isTi" class="approval-card">
        <h3 class="card-title">审批结果</h3>
        <div class="approval-form">
          <div class="form-item">
            <label class="required"><span>*</span>审批结果</label>
            <el-radio-group v-model="approvalResult">
              <el-radio label="0">审批通过</el-radio>
              <el-radio label="1">审批拒绝</el-radio>
              <el-radio label="2">驳回</el-radio>
            </el-radio-group>
          </div>
          <div class="form-item">
            <label class="required"><span>*</span>审批意见</label>
            <el-input
                v-model="approvalOpinion"
                type="textarea"
                placeholder="请输入"
                :maxlength="200"
                show-word-limit
                rows="3"
                style="margin-top: 20px"
            />
          </div>
        </div>
      </div>

      <!-- 操作记录卡片 -->
      <div v-if="log.activities" class="record-card" style="margin-top: 20px;">
        <h3 class="card-title">操作记录</h3>
        <ul class="record-list">
          <li v-for="item in log.activities" class="record-item">
            <div class="item-icon">
              <!-- 替换为“发起申请”图标 -->
              <img src="@/assets/images/avatar.jpg" alt="发起申请" />
            </div>
            <div class="item-content">
              <div class="item-desc">({{ log[item.assignee]?.remark }}){{item.name}}</div>
              <div class="item-status"> {{ log[item.assignee]?.nickName }} （已发起）</div>
              <div v-if="log[item.id] " class="approval-opinion">{{log[item.id].fullMessage ? log[item.id].fullMessage :"无"}}</div>
            </div>
            <div class="item-time">{{item.endTime ? formatDateStr(item.endTime):""}}</div>
          </li>

        </ul>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="btn-area">
      <el-button type="default" @click="goBack">返回</el-button>
      <el-button v-if="isTi" type="primary" @click="submitApproval">提交</el-button>
    </div>
  </div>
</template>

<script>
import {checkOutDto, approval, getActivityLog} from "@/api/check/checkout.js"
export default {
  name: "ApprovalPage",
  data() {
    return {
      isTi: true,
      checkoutDtoInfo:{},
      approvalResult: "", // 绑定审批结果（默认“审批通过”）
      approvalOpinion: "", // 绑定审批意见
      billJson: {},
      refundBill: {},
      total: 0,
      log: {},

    };
  },
  methods: {

    goBack() {
      this.$router.push("/CollaborationWork/tasking"); // 路由回退
    },
    submitApproval() {
      console.log(this.approvalResult)
      if(this.approvalResult!==""){
        const data = {
          checkoutId: this.checkoutDtoInfo.id,
          num: this.approvalResult,
          comment: this.approvalOpinion
        };

        approval( data).then(res => {
          this.isTi = false;
          getActivityLog(this.id).then( res=>{
            this.log = res.data
            this.log.activities=res.data.activities.reverse()
            console.log(res)
          })
          this.$message.success("提交成功");
        })
      }


      // 此处可添加表单验证与提交逻辑

    },
    formatDate(dateStr) {
      if (!dateStr) return '——';
      return new Date(dateStr).toISOString().split('T')[0];
    },
    getCareLevelName(code) {
      const levels = {
        1: '一级护理',
        2: '二级护理',
        3: '三级护理',
        4: '特级护理',
      };
      return levels[code] || '未知';
    },
    formatDateTime(dateStr) {
      if (!dateStr) return '——';
      const d = new Date(dateStr);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`;
    },
    formatDateStr(dateStr) {
      // 1. 基础校验：判断是否为有效字符串且包含关键符号
      if (!dateStr || typeof dateStr !== 'string' || !dateStr.includes('T')) {
        console.warn('输入不是有效的日期格式（需包含"T"，如2025-10-23T10:42:42.000+08:00）');
        return '';
      }

      // 2. 截取核心部分：年月日（T之前） + 时分秒（T之后、.之前）
      // 例："2025-10-23T10:42:42.000+08:00" → 拆分为 ["2025-10-23", "10:42:42.000+08:00"]
      const datePart = dateStr.split('T')[0]; // 取"T"前的年月日："2025-10-23"
      const timePart = dateStr.split('T')[1].split('.')[0]; // 取"T"后、"."前的时分秒："10:42:42"

      // 3. 重组为 "年月日 时分秒" 格式
      return `${datePart} ${timePart}`;
    },




  },
  mounted() {
    checkOutDto(this.id).then(res => {
      this.checkoutDtoInfo = res.data;
      this.billJson = JSON.parse(res.data.checkoutBill.billJson);
      console.log(this.billJson.refundBill.good);
      this.refundBill = this.billJson.refundBill;
      const bill = this.billJson; // 简化变量名，方便使用

      // 步骤1：计算「应退小计」= 月度账单可退金额 + 所有费用账单可退金额
      const refundTotal = (bill.monthBill?.refundAmount1 || 0) +
          bill.refundBill.good.reduce((sum, item) => sum + (item.payableAmount || 0), 0);

      // 步骤2：计算「欠费小计」= 所有欠费月度账单应付金额总和
      const unPayTotal = bill.unPayBill.month.reduce((sum, item) => sum + (item.payableAmount || 0), 0);

      // 步骤3：计算最终 total = 应退小计 + 余额实退金额 - 欠费小计
      this.total= refundTotal +this.checkoutDtoInfo.balance.prepaidBalance+ bill.refundAmount2 - unPayTotal;
    });
    getActivityLog(this.id).then( res=>{
      this.log = res.data
      this.log.activities=res.data.activities.reverse()
      console.log(res)
    })


  },

  props: {
    id: {
      type: [Number,String],
      default: 0,
    },
  },


};
</script>

<style scoped>
.approval-page {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  padding: 20px;
}

.left-column {
  width: 65%;
}

.right-column {
  width: 33%;
}

.info-card,
.approval-card,
.record-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
}

.info-list {
  list-style: none;
  padding: 0;
}

/* 标签右对齐样式 */
.info-list li {
  display: flex;
  margin-bottom: 15px;
}

.info-list .label {
  width: 120px;
  text-align: right;
  margin-right: 15px;
  color: #606266;
}

.info-list .value {
  flex: 1;
}

.view-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 5px;
}

/* 账单明细样式 */
.bill-section {
  border: 1px dashed #ebeef5;
  padding: 15px;
  background-color: #fafafa;
}

.section-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-weight: bold;
}

.todo-count,
.total-amount {
  font-size: 12px;
  color: #909399;
}

.bill-item {
  border: 1px solid #ebeef5;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #fff;
}

.final-amount {
  text-align: center;
  margin-top: 15px;
  font-size: 12px;
  color: #909399;
}

/* 审批表单样式 */
.approval-form .form-item {
  margin-bottom: 15px;
}

.required {
  color: #000000;
  font-size: 16px;
  font-weight: 400;
  margin-right: 10px;
}

/* 操作记录核心样式（流程线 + 布局） */
.record-list {
  list-style: none;
  padding: 0;
  position: relative; /* 作为伪元素的定位容器 */
}

.record-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 30px;
}

/* 垂直主线：连接所有记录项（除第一个），从头像中间穿过 */
.record-item:not(:first-child)::before {
  content: '';
  position: absolute;
  left: 20px; /* 与40px宽图标中心对齐 */
  top: 0;
  height: 100%;
  width: 1px;
  background-color: #dcdcdc;
}

.item-icon {
  margin-right: 12px;
}

.item-icon img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.item-content {
  flex: 1;
}

.item-desc {
  font-weight: 500;
  margin-bottom: 2px;
}

.item-status {
  color: #909399;
  font-size: 12px;
}

/* 审批意见提示框 */
.approval-opinion {
  background-color: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
  margin-top: 5px;
  font-size: 12px;
  color: #606266;
}

.item-time {
  color: #909399;
  font-size: 12px;
  white-space: nowrap; /* 防止时间换行 */
}

/* 底部按钮 */
.btn-area {
  margin-top: 40px;
  text-align: center;
  width: 100%;
}

.btn-area button {
  margin: 0 10px;
}

/* 账单类型样式（蓝色可点击） */
.bill-type {
  color: #409eff;
  cursor: pointer;
}
</style>